/*
 * Copyright 1999-2022 Alibaba Group Holding Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.alibaba.nacos.plugin.datasource.dialect;

import com.alibaba.nacos.plugin.datasource.constants.DataSourceConstant;

/**
 * Oracle database dialect.
 *
 * @author huangchangjin
 */
public class OracleDatabaseDialect extends AbstractDatabaseDialect {

    @Override
    public String getType() {
        return DataSourceConstant.ORACLE;
    }

    @Override
    public String getLimitTopSqlWithMark(String sql) {
        return "SELECT * FROM ( SELECT TMP.*, ROWNUM ROW_ID FROM ( " + sql + " ) TMP WHERE ROWNUM <= ? ) WHERE ROW_ID > 0";
    }

    @Override
    public String getLimitPageSqlWithMark(String sql) {
        // 注意原始sql的占位符的顺序
        return "SELECT * FROM ( SELECT TMP.*, ROWNUM ROW_ID FROM ( " + sql + " ) TMP ) WHERE ROW_ID > ? and ROW_ID <= ?";
    }

    @Override
    public String getLimitPageSql(String sql, int pageNo, int pageSize) {
        int startOffset = getPagePrevNum(pageNo, pageSize);
        int endNum = (startOffset >= 1) ? (startOffset + pageSize) : pageSize;
        return "SELECT * FROM ( SELECT TMP.*, ROWNUM ROW_ID FROM ( " + sql + " ) TMP WHERE ROWNUM <= " + endNum + " ) WHERE ROW_ID > " + startOffset;
    }

    @Override
    public String getLimitPageSqlWithOffset(String sql, int startOffset, int pageSize) {
        int endNum = (startOffset >= 1) ? (startOffset + pageSize) : pageSize;
        return "SELECT * FROM ( SELECT TMP.*, ROWNUM ROW_ID FROM ( " + sql + " ) TMP WHERE ROWNUM <= " + endNum + " ) WHERE ROW_ID > " + startOffset;
    }

}
